package com.bajiao.app.task;

import com.bajiao.common.constant._Whole;
import com.bajiao.common.util.DateUtils;
import com.bajiao.common.util.RedisUtil;
import com.bajiao.entity.user.UserCoupon;
import com.bajiao.service.user.UserCouponService;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Component
@Configuration //读取配置
public class CouponExpireTask {

    @Resource
    private UserCouponService userCouponService;
    @Resource
    private RedisUtil redisUtil;

    //@create by FanJq 2024/7/10 11:30 每天凌晨0点执行
    @Scheduled(cron = "0 0 0 * * ?")
    public void init() {
        //@create by FanJq 2024/12/20 15:02 获取今日过期的
        List<UserCoupon> resultList = userCouponService.getTodayExpire();
        resultList.forEach(model -> {
            //@create by FanJq 2024/12/19 10:25 计算到期时间 加入redis订阅队列
            long seconds = DateUtils.secondsBetween(new Date(), model.getExpireTime());
            String key = _Whole.couponExpiredKey + model.getId();
            redisUtil.set(key, model.getId(), seconds);
        });
        //@create by FanJq 2024/12/20 15:02 获取已过期的
        List<UserCoupon> expiredList = userCouponService.getExpired();
        expiredList.forEach(model -> {
            //@create by FanJq 2024/12/20 15:05 已过期的直接执行过期事件
            userCouponService.expiredEvent(model);
        });
    }
}
